package ${baseInfo.basePackage}.${baseInfo.moduleName}.controller;

import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import java.io.PrintWriter;
import net.sf.json.JSONObject;
import java.nio.charset.StandardCharsets;
import ${baseInfo.basePackage}.${baseInfo.moduleName}.model.${baseInfo.classForClassName};
import ${baseInfo.basePackage}.${baseInfo.moduleName}.service.${baseInfo.classForClassName}Service;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;
import java.util.ArrayList;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
<#if selectFlow?? && selectFlow != "">
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
</#if>

/**
 * ${baseInfo.tableComment} 信息操作处理控制器
 * 
 * @author ${baseInfo.author}
 * @date ${baseInfo.datetime}
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "${baseInfo.tableComment}")
@RequestMapping("/${baseInfo.moduleName}/${baseInfo.classForPrefix}")
public class ${baseInfo.classForClassName}Controller extends SysBaseController{
	@Resource
	private ${baseInfo.classForClassName}Service ${baseInfo.classForPrefix}Service;
<#if selectFlow?? && selectFlow != "">
    @Resource
    private ProcessRunService processRunService;
</#if>

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: ${baseInfo.author}
     * @date: ${baseInfo.datetime}
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到${baseInfo.tableComment}首页", exectype = "页面跳转日志")
    public String viewList() {
        <#if baseInfo.showFull?? && baseInfo.showFull>
        return "/iframe/link/${baseInfo.classForPrefix}List";
        <#else>
        return "${baseInfo.classForPrefix}/list";
        </#if>
    }
    <#if baseInfo.showFull?? && baseInfo.showFull>
    /**
    * 功能描述: 跳转页面
    *
    * @return: java.lang.String
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/lists")
    @Action(description="跳转页面", exectype = "页面跳转日志")
    public String viewLists() {
        return "${baseInfo.classForPrefix}/list";
    }
    </#if>

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询${baseInfo.tableComment}",detail="查询数据信息<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else></<#noparse>#</#noparse>if>")
    public Object list(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        //分页数据
        List<${baseInfo.classForClassName}> pageDatas = ${baseInfo.classForPrefix}Service.queryList(queryFilter);
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: ${baseInfo.author}
     * @date: ${baseInfo.datetime}
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到${baseInfo.tableComment}新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String ${baseInfo.primaryKey.attrNameForProperty} = RequestUtil.getString(request,"${baseInfo.primaryKey.attrNameForProperty}");
        modelMap.put("${baseInfo.primaryKey.attrNameForProperty}",${baseInfo.primaryKey.attrNameForProperty});
        <#if selectFlow?? && selectFlow != "">
        String runId = RequestUtil.getString(request,"runId");
        modelMap.put("runId",runId);
        </#if>
        return "${baseInfo.classForPrefix}/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: ${baseInfo.classForPrefix} 保存的对象
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存${baseInfo.tableComment}数据",detail="<<#noparse>#</#noparse>if isAdd>新增<<#noparse>#</#noparse>else>编辑</<#noparse>#</#noparse>if>${baseInfo.tableComment}数据<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else>失败</<#noparse>#</#noparse>if>")
    public Object save(@RequestBody ${baseInfo.classForClassName} ${baseInfo.classForPrefix}) {
        ${baseInfo.primaryKey.attrType} id = ${baseInfo.classForPrefix}.get${baseInfo.primaryKey.attrNameForMethod}();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机${baseInfo.primaryKey.attrNameForMethod}
            <#if baseInfo.primaryKey.attrType == "String">
            ${baseInfo.classForPrefix}.set${baseInfo.primaryKey.attrNameForMethod}(UUIDUtils.getUUIDFor32());
            <#elseif baseInfo.primaryKey.attrType == "Long">
            ${baseInfo.classForPrefix}.set${baseInfo.primaryKey.attrNameForMethod}(UUIDUtils.getLongId());
            </#if>
            <#list baseInfo.columns as column>
            <#if column.columnName == "tenantid">
            ${baseInfo.classForPrefix}.setTenantId(ContextUtil.getCurrentUserTenantId());
            </#if>
            <#if column.columnName == "createby">
            ${baseInfo.classForPrefix}.setCreateBy(ContextUtil.getCurrentUserId());
            </#if>
            <#if column.columnName == "createtime">
            ${baseInfo.classForPrefix}.setCreateTime(new Date());
            </#if>
            </#list>
            result = ${baseInfo.classForPrefix}Service.add(${baseInfo.classForPrefix});
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            <#list baseInfo.columns as column>
            <#if column.columnName == "updateby">
            ${baseInfo.classForPrefix}.setUpdateBy(ContextUtil.getCurrentUserId());
            </#if>
            <#if column.columnName == "updatetime">
            ${baseInfo.classForPrefix}.setUpdateTime(new Date());
            </#if>
            </#list>
            //修改操作
            result = ${baseInfo.classForPrefix}Service.update(${baseInfo.classForPrefix});
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到${baseInfo.tableComment}详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String ${baseInfo.primaryKey.attrNameForProperty} = RequestUtil.getString(request,"${baseInfo.primaryKey.attrNameForProperty}");
        modelMap.put("${baseInfo.primaryKey.attrNameForProperty}",${baseInfo.primaryKey.attrNameForProperty});
        return "${baseInfo.classForPrefix}/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"${baseInfo.primaryKey.attrNameForProperty}"
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询${baseInfo.tableComment}的一条数据",detail="根据主键id查询${baseInfo.tableComment}的数据<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else>失败</<#noparse>#</#noparse>if>")
    public Object get(@RequestParam("id") String ${baseInfo.primaryKey.attrNameForProperty}) {
        <#if baseInfo.primaryKey.attrType == "Long">
        Long ${baseInfo.primaryKey.attrNameForProperty}ToLong = Long.parseLong(${baseInfo.primaryKey.attrNameForProperty});
        ${baseInfo.classForClassName} ${baseInfo.classForPrefix} = ${baseInfo.classForPrefix}Service.getOneById(${baseInfo.primaryKey.attrNameForProperty}ToLong);
        <#elseif baseInfo.primaryKey.attrType == "String">
        ${baseInfo.classForClassName} ${baseInfo.classForPrefix} = ${baseInfo.classForPrefix}Service.getOneById(${baseInfo.primaryKey.attrNameForProperty});
        </#if>
        if (null == ${baseInfo.classForPrefix}) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",${baseInfo.classForPrefix});
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"${baseInfo.primaryKey.attrNameForProperty}"
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除${baseInfo.tableComment}数据",exectype = "删除日志",detail="删除数据信息<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else>失败</<#noparse>#</#noparse>if>")
    public Object delete(@RequestParam("id") String ${baseInfo.primaryKey.attrNameForProperty}) {
        if (StringUtil.isEmpty(${baseInfo.primaryKey.attrNameForProperty})) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        int result = ${baseInfo.classForPrefix}Service.delByIdArray(${baseInfo.primaryKey.attrNameForProperty}.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2019-12-25 19:21:40
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到${baseInfo.tableComment}导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "${baseInfo.classForPrefix}/import";
    }

    /**
    * 功能描述: 导出${baseInfo.tableComment}数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: ${baseInfo.author}
    * @date: ${baseInfo.datetime}
    */
    @RequestMapping("/exportData")
    @Action(description="导出${baseInfo.tableComment}数据信息",detail="导出${baseInfo.tableComment}数据信息<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else></<#noparse>#</#noparse>if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String[] id = RequestUtil.getStringAryByStr(request,"id");
        QueryFilter queryFilter = new QueryFilter(request,false);
        if(BeanUtils.isNotEmpty(id) && id.length!=0){
            queryFilter.put("byId",true);
            queryFilter.put("id",id);
        }else{
            queryFilter.put("byId",false);
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        Excel excel = new Excel();
        String fileName = "${baseInfo.classForClassName}";//导出的文件名称
        excel.sheet().sheetName("sheet");// 重命名当前处于工作状态的表的名称
        List<String> titleList = new ArrayList<>();
        <#list baseInfo.columns as column>
        titleList.add("${column.columnComment}");
        </#list>
        excel.row(0, 0).value(titleList.toArray());
        excel.row(0,0).font(new IFontEditor() {
            // 设置字体
            @Override
            public void updateFont(Font font) {
                font.boldweight(BoldWeight.BOLD);// 粗体
            }
        }).bgColor(Color.GREY_25_PERCENT).width(3500);
        excel.row(0, 1).width(3500);
        excel.row(0, 2).width(3500);
        excel.row(0, 3).width(3500);
        excel.row(0, 4).width(3500);
        //设置列的数据格式
        excel.sheet().setDefaultColumnStyle(0, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(1, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(2, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(3, DataFormat.TEXT);
        ExcelUtil.downloadExcel(${baseInfo.classForPrefix}Service.exportExcel(excel,queryFilter), fileName, response);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    public void importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        MultipartFile multipartFile = request.getFile("file");
        PrintWriter writer = response.getWriter();
        try {
            String fileName = multipartFile.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            //读取excel文件，并获取每行的数据
            ExcelReader excelReader = new ExcelReader();
            TableEntity excelEntity = excelReader.readFile(multipartFile.getInputStream());
            List<DataEntity> rowDataEntityList = excelEntity.getDataEntityList();

            List<${baseInfo.classForClassName}> listToInsert = new ArrayList<>();
            for (DataEntity dataEntity : rowDataEntityList) {
                //获取每列的数据
                List<FieldEntity> fieldEntityList = dataEntity.getFieldEntityList();
                ${baseInfo.classForClassName} dataToInsert = new ${baseInfo.classForClassName}();
                int i =0;
                //根据列的顺序，给相应的对象赋值
                for (FieldEntity fieldEntity : fieldEntityList) {
                    //if(i==0){
                        //dataToInsert.setName(fieldEntity.getValue());
                    //}
                    i++;
                }
                dataToInsert.set${baseInfo.primaryKey.attrNameForMethod}(UUIDUtils.getUUIDFor32());
                listToInsert.add(dataToInsert);
            }
            ${baseInfo.classForPrefix}Service.addList(listToInsert);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("operation.success"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            JSONObject json = JSONObject.fromObject(getResultDataError("operation.failure"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
        }
    }

    <#if selectFlow?? && selectFlow != "">
    /**
     * 功能描述: 跳转至modify页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/modify")
    @Action(description="跳转到${baseInfo.tableComment}modify页面")
    public String viewModify(HttpServletRequest request,ModelMap modelMap) {
        String ${baseInfo.primaryKey.attrNameForProperty} = RequestUtil.getString(request,"${baseInfo.primaryKey.attrNameForProperty}");
        modelMap.put("${baseInfo.primaryKey.attrNameForProperty}",${baseInfo.primaryKey.attrNameForProperty});
        return "${baseInfo.classForPrefix}/modify";
    }

    /**
     * 功能描述: 跳转至detail页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/detail")
    @Action(description="跳转到${baseInfo.tableComment}detail页面")
    public String viewDetail(HttpServletRequest request,ModelMap modelMap) {
        String ${baseInfo.primaryKey.attrNameForProperty} = RequestUtil.getString(request,"${baseInfo.primaryKey.attrNameForProperty}");
        modelMap.put("${baseInfo.primaryKey.attrNameForProperty}",${baseInfo.primaryKey.attrNameForProperty});
        return "${baseInfo.classForPrefix}/detail";
    }

    /**
    * 功能描述: 启动流程
    */
    @PostMapping("/run")
    @ResponseBody
    @Action(description="启动${baseInfo.tableComment}流程",detail="启动流程<<#noparse>#</#noparse>if success>成功<<#noparse>#</#noparse>else></<#noparse>#</#noparse>if>")
    public Object run(HttpServletRequest request,@RequestBody ${baseInfo.classForClassName} ${baseInfo.classForPrefix}){
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //实体主键
        String ${baseInfo.primaryKey.attrNameForProperty} = ${baseInfo.classForPrefix}.get${baseInfo.primaryKey.attrNameForMethod}();
        int isList = RequestUtil.getInt(request,"isList",1);
        ProcessCmd  processCmd = new ProcessCmd();
        //流程Key
        processCmd.setModelKey("${selectFlow}");
        processCmd.setUserAccount(sysUser.getAccount());
        try {
            if(StringUtil.isNotEmpty(${baseInfo.primaryKey.attrNameForProperty})){
                if(isList == 1){
                    ${baseInfo.classForPrefix} = ${baseInfo.classForPrefix}Service.getOneById(${baseInfo.primaryKey.attrNameForProperty});
                }
                processCmd.setBusinessKey(${baseInfo.primaryKey.attrNameForProperty});
                processRunService.startProcess(processCmd);
                <#list baseInfo.columns as column>
                <#if column.columnName == "updateBy">
                ${baseInfo.classForPrefix}.setUpdateBy(ContextUtil.getCurrentUserId());
                </#if>
                <#if column.columnName == "updateTime">
                ${baseInfo.classForPrefix}.setUpdateTime(new Date());
                </#if>
                </#list>
                ${baseInfo.classForPrefix}Service.update(${baseInfo.classForPrefix});
            }else{
                String genId = UUIDUtils.getUUIDFor32();
                processCmd.setBusinessKey(genId);
                ${baseInfo.classForPrefix}.set${baseInfo.primaryKey.attrNameForMethod}(genId);
                String tenantId = ContextUtil.getCurrentUserTenantId();
                processRunService.startProcess(processCmd);
                <#list baseInfo.columns as column>
                <#if column.columnName == "tenantId">
                ${baseInfo.classForPrefix}.setTenantId(ContextUtil.getCurrentUserTenantId());
                </#if>
                <#if column.columnName == "createBy">
                ${baseInfo.classForPrefix}.setCreateBy(ContextUtil.getCurrentUserId());
                </#if>
                <#if column.columnName == "createTime">
                ${baseInfo.classForPrefix}.setCreateTime(new Date());
                </#if>
                </#list>
                ${baseInfo.classForPrefix}Service.add(${baseInfo.classForPrefix});
            }
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("flow.start.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("flow.start.failure");
        }
    }
    </#if>

}
